package cn.walls1717.wallsmall.cart.controller;

import cn.walls1717.wallsmall.cart.service.CartService;
import cn.walls1717.wallsmall.cart.vo.CartItemVO;
import cn.walls1717.wallsmall.cart.vo.CartVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 购物车
 *
 * @author walls1717
 * @since 2022/11/15 9:07
 **/
@Controller
@Slf4j
public class CartController {
    @Resource
    private CartService cartService;

    /** 获取当前用户购物车中的所有购物项 */
    @GetMapping("/currentUserCartItems")
    @ResponseBody
    public List<CartItemVO> listCurrentUserCartItems() {
        return cartService.listCurrentUserCartItems();
    }

    /** 删除购物项 */
    @GetMapping("/deleteItem")
    public String deleteCartItem(@RequestParam("skuId") Long skuId) {
        cartService.removeCartItemBySkuId(skuId);
        return "redirect:http://cart.wallsmall.com/cart.html";
    }

    /** 修改购物项数量 */
    @GetMapping("/countItem")
    public String updateCount(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num) {
        cartService.updateCountBySkuId(skuId, num);
        return "redirect:http://cart.wallsmall.com/cart.html";
    }

    /** 购物项选中状态 */
    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId, @RequestParam("checked") Integer check) {
        cartService.updateCheckBySkuId(skuId, check);
        return "redirect:http://cart.wallsmall.com/cart.html";
    }

    /** 购物车页 */
    @GetMapping("/cart.html")
    public String carListPage(Model model) throws ExecutionException, InterruptedException {
        CartVO cart = cartService.getCart();
        model.addAttribute("cart", cart);
        return "cartList";
    }

    /** 添加商品到购物车 */
    @GetMapping("/addCartItem")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes attributes)
        throws ExecutionException, InterruptedException {

        cartService.saveCartItem(skuId, num);
        attributes.addAttribute("skuId", skuId);
        return "redirect:http://cart.wallsmall.com/addToCartSuccess.html";
    }

    /** 添加购物车成功跳转成功页面 */
    @GetMapping("/addToCartSuccess.html")
    public String addToCartSuccessPage(@RequestParam("skuId") Long skuId, Model model) {
        CartItemVO cartItemVO = cartService.getCartItemBySkuId(skuId);
        model.addAttribute("cartItem", cartItemVO);
        return "success";
    }
}
